package com.example.chenhuamou.freenews.view.news;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.chenhuamou.freenews.R;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by chenhuamou on 2017/9/14.
 */

public class NewsFragment extends android.support.v4.app.Fragment implements ViewPager.OnPageChangeListener {


    @BindView(R.id.tabs)
    TabLayout mTabs;
    @BindView(R.id.viewPager)
    ViewPager mViewPager;

    private String[] titles = {"头条", "NBA", "汽车", "笑话"};

    private NewsListFragment[] mFragments;
    public int currentIndex = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news, container, false);
        ButterKnife.bind(this, view);
        initView();
        return view;
    }



    // 初始化View
    private void initView() {
        mTabs.setTabMode(TabLayout.MODE_FIXED);
        // 这里是 getChildFragmentManager，嵌套了fragment，里面的滑动会冲突
        mViewPager.setAdapter(new NewListAdapter(getChildFragmentManager()));
        mTabs.setupWithViewPager(mViewPager);
        mViewPager.addOnPageChangeListener(this);
    }

    // viewPager page change listener
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        currentIndex = position;
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    // viewPager adapter
    public class NewListAdapter extends FragmentPagerAdapter {

        public NewListAdapter(FragmentManager fragmentManager) {
            super(fragmentManager);
        }

        /**
         * Return the Fragment associated with a specified position.
         *
         * @param position
         */
        @Override
        public Fragment getItem(int position) {
            NewsListFragment fragment = new NewsListFragment();
            return fragment;
        }

        /**
         * Return the number of views available.
         */
        @Override
        public int getCount() {
            return titles.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }
    }

}
